import Loader from "../../Common/Loader";
import Frame from "../frameNamespace";
import { mgrs, sers } from "../system/OverallSystem ";

interface SoundPlayInfo {
    name: string;
    loop: boolean;
}

export default class SoundManager extends Frame.ManagerBase {
    protected _managerName: string = "音频管理";

    constructor() {
        super();

        this._Initialize();
        let d = sers().userSrv.getSettingData()
        this._isEnableAudio = d[0]
        this._isEnableSound = d[1]
        this._isVibration = d[2]
        this._isRensheng = d[3]
        this._isFangyan = d[4]
        
    }

    _Initialize(): void {
        super._Initialize();
    }

    private previousMusic: SoundPlayInfo = undefined;

    private _isEnableAudio: boolean = true;
    get isEnableAudio() { return this._isEnableAudio; }

    private _isEnableSound: boolean = true;
    get isEnableSound() { return this._isEnableSound; }

    private _isVibration: boolean = true;
    get isVibration() { return this._isVibration; }

    private _isRensheng: boolean = true;
    get isRensheng() { return this._isRensheng; }

    private _isPlayMusic: boolean = false;
    get isPlayMusic() { return this._isPlayMusic; }

    private _isFangyan: boolean = true;
    get isFangyan() { return this._isFangyan; }

    enableAudio(enable: boolean = true) {
        this._isEnableAudio = enable;
        let d = sers().userSrv.getSettingData()
        d[0]= this._isEnableAudio
        sers().userSrv.setSettingData(d)
        if (!this._isEnableAudio) {
            this.stopMusic();
            this.stopAllSound();
        } else {
            this.playPreviousMusic();
        }
    }

     /**
     * 设置音效开关。 比如按钮
     * @param enable 
     */
    enableSound(enable: boolean = true) {
        this._isEnableSound = enable;
        let d = sers().userSrv.getSettingData()
        d[1]= this._isEnableSound
        sers().userSrv.setSettingData(d)
    }

     /**
     * 设置震动开关。 比如按钮
     * @param enable 
     */
    enableVibration(enable: boolean = true) {
        this._isVibration = enable;
        let d = sers().userSrv.getSettingData()
        d[2]= this._isVibration
        sers().userSrv.setSettingData(d)
    }

     /**
     * 设置rensheng开关。 比如按钮
     * @param enable 
     */
     enableRensheng(enable: boolean = true) {
        this._isRensheng = enable;
        let d = sers().userSrv.getSettingData()
        d[3]= this._isRensheng
        sers().userSrv.setSettingData(d)
    }


     /**
     * 设置方言开关。 
     * @param enable 
     */
     enableFangyan(enable: boolean = true) {
        this._isFangyan = enable;
        let d = sers().userSrv.getSettingData()
        d[4]= this._isFangyan
        sers().userSrv.setSettingData(d)
    }



    private getAudioClipWithSoundBundle(audioName: string) {
        return new Promise<cc.AudioClip>((resolve, reject) => {
            mgrs().bundleMgr.BundleList.soundBundle.load(audioName, cc.AudioClip, (error: Error, ac: cc.AudioClip) => {
                if (error) {
                    cc.log(audioName)
                    console.error("从默认音频bundle获取音频失败");
                    // reject();
                    return;
                }
                resolve(ac);
            });
        });
    }

    fangyan = -1
    pengzhuang = false
    playSound(soundName: string, loop: boolean = false,time=50) {
        return new Promise<number>((resolve, reject) => {
            if (!this._isEnableSound) {
                // reject();
                return;
            }
            
            cc.log(soundName)
            let old =soundName
            let fy = ['hu','chi','peng','gang']
            if(fy.indexOf(soundName)>=0){
                let d = sers().userSrv.getSettingData()
                let check = d[5] || ''
                soundName+= check
                if(+check == 2 && Math.random()<0.5){
                    soundName +='-'
                }
                cc.log(soundName)
                if(this.fangyan){
                    cc.log('停止上一个音效')
                    cc.audioEngine.stopEffect(this.fangyan)
                    this.fangyan = -1
                }
            }

            if(soundName == 'pengzhuang'){
                if(this.pengzhuang){
                    return
                }
                this.pengzhuang = true
                setTimeout(() => {
                    this.pengzhuang = false
                }, time);
            }

            this.getAudioClipWithSoundBundle(soundName).then((ac: cc.AudioClip) => {
                let audioID = cc.audioEngine.playEffect(ac, loop);
                if(fy.indexOf(old)>=0){
                    this.fangyan = audioID
                }
                resolve(audioID);
            }).catch(() => {
                console.warn(loop ? "循环" : "" + "播放" + soundName + "失败!!");
                // reject();
            });
        });
    }


    shangyige = 'bgm'
    playMusic(musicName: string, loop: boolean = true) {
        if (this._isPlayMusic) {
            this.stopMusic();
        }
        return new Promise<number>((resolve, reject) => {
            if (!this._isEnableAudio) {
                // reject();
                return;
            }

            this.getAudioClipWithSoundBundle(musicName).then((ac: cc.AudioClip) => {
                let audioID = cc.audioEngine.playMusic(ac, loop);
                this._isPlayMusic = true;
                this.shangyige = musicName
                this.previousMusic = {
                    name: musicName,
                    loop: loop,
                }
                resolve(audioID);
            }).catch(() => {
                console.warn(loop ? "循环" : "" + "播放" + musicName + "失败!!");
                // reject();
            });
        });
    }

    playBtnSound(){
        return this.playSound("click");
    }

    stopMusic() {
        this._isPlayMusic = false;
        cc.audioEngine.stopMusic();
    }
    stopAllSound() {
        cc.audioEngine.stopAllEffects();
    }
    stopSound(audioID: number) {
        cc.audioEngine.stopEffect(audioID);
    }
    playPreviousMusic() {
        if (this.previousMusic != undefined) {
            let { name, loop } = this.previousMusic;
            if (name != null && name != "") {
                this.playMusic(name, loop);
            }
        }
    }



    private getAudioClipWithSoundBundle2(audioName: string,BundleName:string) {
        return new Promise<cc.AudioClip>((resolve, reject) => {
            Loader.loadBundle(BundleName, (res) => {
               
                Loader.loadBundleDir(BundleName, "sound", (res) => {                    
                    
                    let y = false
                    for (const iterator of res) {
                        if(iterator.name == audioName){
                            y=true
                            resolve(iterator);
                        }
                    }
                    if(y)return
                    // reject();

                }, cc.AudioClip, true);
            }, true, true);

            // BundleName.load(audioName, cc.AudioClip, (error: Error, ac: cc.AudioClip) => {
            //     if (error) {
            //         console.error("从默认音频bundle获取音频失败");
            //         reject();
            //         return;
            //     }
            //     resolve(ac);
            // });
        });
    }

    playSound2(soundName: string,BundleName, loop: boolean = false) {
        return new Promise<number>((resolve, reject) => {
            if (!this._isEnableSound) {
                // reject();
                return;
            }

            this.getAudioClipWithSoundBundle2(soundName,BundleName).then((ac: cc.AudioClip) => {
                let audioID = cc.audioEngine.playEffect(ac, loop);
                resolve(audioID);
            }).catch(() => {
                console.warn(loop ? "循环" : "" + "播放" + soundName + "失败!!");
                // reject();
            });
        });
    }

    playMusic2(musicName: string,BundleName, loop: boolean = true) {
        if (this._isPlayMusic) {
            this.stopMusic();
        }
        return new Promise<number>((resolve, reject) => {
            if (!this._isEnableAudio) {
                // reject();
                return;
            }

            this.getAudioClipWithSoundBundle2(musicName,BundleName).then((ac: cc.AudioClip) => {
                let audioID = cc.audioEngine.playMusic(ac, loop);
                this._isPlayMusic = true;
                this.shangyige = musicName
                this.previousMusic = {
                    name: musicName,
                    loop: loop,
                }
                resolve(audioID);
            }).catch(() => {
                console.warn(loop ? "循环" : "" + "播放" + musicName + "失败!!");
                // reject();
            });
        });
    }

    
}